package com.ywm.msmService.controller;

import com.ywm.commonUtil.R;
import com.ywm.msmService.service.MsmService;
import com.ywm.msmService.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //发送短信的方法
    @GetMapping("/send{phoneNumber}")
    public R sendMsm(@PathVariable("phoneNumber") String phoneNumber) {
        Map<String,Object> param=new HashMap<>();
        //1.从Redis获取验证码，如果获取到直接返回
        String RCode = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(RCode)) {
            System.out.println(1);
            param.put("code",RCode);
            if (msmService.sendMessage(param, phoneNumber)) {
                return R.ok();
            }else {
                return R.error();
            }
        }
        //生成随机数，发送到验证码
        String code = RandomUtil.getSixBitRandom();
        param.put("code",code);
        //调用service发送短信的方法
        Boolean isSend = msmService.sendMessage(param, phoneNumber);
        System.out.println(2);
        if (isSend) {
            //发送成功，把验证码放进Redis，并设置有效时间
            /**
             * 参数一：key
             * 参数二：value
             * 参数三：时间
             * 参数四：时间单位
             */
            System.out.println(3);
            redisTemplate.opsForValue().set("phone",code, 5,TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }
}
